package com.copro.chemdb.areas;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.db.sql.SQLSegment;

import com.copro.simple.Application;
import com.copro.simple.SimpleException;
import com.copro.simple.db.QueryCallback;

public class AreaUtils {

	static class CityListGetter implements QueryCallback {

		private List<City> list;

		public CityListGetter(List<City> list) {
			this.list = list;
		}

		public List<City> getList() {
			return this.list;
		}

		@Override
		public void exec(ResultSet rs) throws SQLException {
			while (rs.next()) {
				list.add(new City(rs));
			}
		}
	}

	static class ProvinceListGetter implements QueryCallback {

		private List<Province> list;

		public ProvinceListGetter(List<Province> list) {
			this.list = list;
		}

		public List<Province> getList() {
			return this.list;
		}

		@Override
		public void exec(ResultSet rs) throws SQLException {
			while (rs.next()) {
				list.add(new Province(rs));
			}
		}
	}

	static class CityDetailGetter implements QueryCallback {

		private City constType;

		public CityDetailGetter(City constType) {
			this.constType = constType;
		}

		public City getObject() {
			return this.constType;
		}

		@Override
		public void exec(ResultSet rs) throws SQLException {
			if (rs.first())
				this.constType = new City(rs);

		}

	}

	public static List<City> getAllCity(Application app) throws SimpleException {
		CityListGetter callback = new CityListGetter(new LinkedList<City>());
		SQLSegment sql = app.getSQL("allCities");
		app.query(sql.toString(), callback);
		return callback.getList();
	}

	public static List<Province> getAllProvince(Application app) throws SimpleException {
		ProvinceListGetter callback = new ProvinceListGetter(new LinkedList<Province>());
		SQLSegment sql = app.getSQL("allProvinces");
		app.query(sql.toString(), callback);
		return callback.getList();
	}

	public static List<City> getCityByProvince(Application app, int provinceId)
			throws SimpleException {
		CityListGetter callback = new CityListGetter(new LinkedList<City>());
		SQLSegment sql = app.getSQL("provinceCities");
		sql.set("provinceId", provinceId <= 0 ? "NULL" : provinceId);
		app.query(sql.toString(), callback);
		return callback.getList();
	}

	public static City getCityById(Application app, int id)
			throws SimpleException {
		SQLSegment sql = app.getSQL("getConstType");
		sql.set("id", id <= 0 ? "NULL" : id);
		CityDetailGetter callback = new CityDetailGetter(new City());
		app.query(sql.toString(), callback);
		return callback.getObject();
	}
}
